from functools import wraps

from django.conf import settings
from django.http import HttpRequest

from gis.admin import const
from gis.admin.exceptions import ERROR_USER_INVALID_TOKEN
from gis.common.exceptions import BizException
from gis.common.safe_dog import client as safe_dog_client
from gis.common.utils import get_request_ip
from itpay.core.agency.errors import *


def require_vcode(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        request = args[0]
        assert isinstance(request, HttpRequest)
        if not request.session.get(const.SESSION_USER_KEY):
            raise BizException(ERROR_USER_INVALID_TOKEN)

        user_id = request.session[const.SESSION_USER_KEY]
        check_user_vcode(request, user_id)

        return func(*args, **kwargs)

    return wrapper


def check_user_vcode(request, user_id, ip=None):
    if settings.IS_PRODUCTION_ENV:
        ip = ip or get_request_ip(request)
        vcode = request.META.get('HTTP_X_AUTH_VCODE')
        if not vcode:
            raise BizException(ERROR_VCODE_EMPTY)
        if not safe_dog_client.verify_token(user_id, vcode, ip):
            raise BizException(ERROR_VCODE_INCORRECT)
